var express = require('express');
var mysql = require('./mydb.js');
var bodyParser = require('body-parser');
var app = express();
 
var TEST_TABLE = 'user';

app.use(express.static('public'));

app.get('/', function (req, res) {
   res.sendFile(__dirname+'/public/index.html');
})

app.get('/api', function (req, res) {
   	res.send(date);
});

// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.post('/login',urlencodedParser, function (req, res) {
	var url_info = require('url').parse(req.url, true);
	
	var name = req.body.username;
	var pass = req.body.password;
	console.log(name);
	var name1 = url_info.query.username;
	var pass1 = url_info.query.password;
	if(name&&pass){
		console.log(name+"登录");
		var sql = "SELECT * from user where username = '"+name+"'";
		mysql.query(sql, function(err, rows, fields){  
		    if (err) {  
		        console.log(err);
		        res.json({type:"err",result:"用户名错误"});
		        return;
		    }
		    if(rows[0].hasOwnProperty("password")&&rows[0].password == pass){
		    	console.log(name+"登录成功");
		    	var resq = {type:"success",result:"登录成功"}
				res.json(resq);
		    }else{
		    	res.json({type:"err",result:"密码或用户名错误"});
		    }
		});
		
	}else{
		var resq = {type:"err",result:"用户名或密码不能为空"}
		res.send(resq);
	};
});


app.get('/insert', function (req, res) {
	var url_info = require('url').parse(req.url, true);
	var name = url_info.query.username;
	var pass = url_info.query.password;
	if(name&&pass){
		console.log(name+"注册");
		    mysql.query("select * from user where username = '"+name+"'", function(err, rows, fields){  
			    if (err) {  
			        console.log(err);
			        return;
			    }
			    if(rows.length<1){
			    	var sql = "INSERT INTO user (username,password) VALUES ('"+name+"','"+pass+"')";
		    		mysql.query(sql, function(err, rowsa, fields){  
					    if (err) {  
					        console.log(err);
					        res.json({type:"err",result:"错误"});
					        return;
			    		}
			    		console.log(name+"注册成功");
		    			res.json({type:"success",result:"ok"});
		    		});
			    }else{
			    	console.log(name+"注册失败");
			    	res.json({type:"err",result:"错误，用户名重复"});
			    }
			});
	}else{
		var resq = {type:"err",result:"用户名或密码不能为空"}
		res.send(resq);
	};
});
 
var server = app.listen(8083, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
 
})